﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Web;
using SyncCommon;

namespace SyncWebSite
{
    public class SyncAnjuke : SyncHouseBase
    {
        private Dictionary<string, string> loginCookies;
        private List<string> retImages = new List<string>();
        private List<string> retImageDes = new List<string>();
        private List<string> retImageName = new List<string>();
        private string targetID;
        private string CityID;
        private string CityShort;

        public SyncAnjuke(string user, string password)
            : base(user, password)
        {

        }
        #region ISyncHouse

        public override bool CheckLogin()
        {
            string status = "";
            WebRequest request = new WebRequest("http://my.anjuke.com/login/");
            request.GetResouceStr();
            loginCookies = request.Cookies;

            string loginurl = "http://my.anjuke.com/usercenter/login";
            request = new WebRequest(loginurl, FormType.FormUrlEncode, Encoding.UTF8, Encoding.UTF8);

            request.AddContent("act", "login");
            request.AddContent("formhash", "1");
            request.AddContent("submit", "");
            request.AddContent("loginpost", "1");
            request.AddContent("sid", "anjuke");
            request.AddContent("systemtime", "1323929714");
            request.AddContent("url", "aHR0cDovL215LmFuanVrZS5jb20vdXNlci9icm9rZXJwcm9wbWFuYWdlL1cwUVFhY3Rac2FsZQ==");

            request.AddContent("username", UserName);
            request.AddContent("password", Password);
            status = request.SendWaitString();

            loginCookies = request.Cookies;
            if (status.Contains("登录成功"))
            {

                status = status.Replace("&amp;", "&");
                status = status.Replace("&iuml;&raquo;&iquest;No1Meaning1=1&", "");
                //Regex reg = new Regex("(?<=img src=').*?no_redirect=1");
                Regex reg = new Regex("\\<img\\s*?src=['\"](?<href>[\\s\\S]*?)[\"']");
                MatchCollection matchs = reg.Matches(status);
                foreach (Match ma in matchs)
                {
                    if (!string.IsNullOrEmpty(ma.Value))
                    {
                        try
                        {
                            string str = HttpUtility.HtmlDecode(ma.Groups["href"].Value ?? "");

                            request = new WebRequest(str);
                            request.SetHeaderValue("Referer", loginurl);
                            request.Cookies = loginCookies;
                            request.GetResouceStr();
                        }
                        catch (Exception exp)
                        {

                        }
                    }
                }

                Regex regex2 = new Regex("content=\"0;URL=(?<href>[\\s\\S]*?)\"");
                if (regex2.IsMatch(status))
                {
                    MatchCollection matchs2 = regex2.Matches(status);
                    foreach (Match ma in matchs2)
                    {
                        if (!string.IsNullOrEmpty(ma.Value))
                        {
                            string str = HttpUtility.HtmlDecode(ma.Groups["href"].Value ?? "");
                            request = new WebRequest(str);
                            request.AllowRedirect = false;
                            request.SetHeaderValue("Referer", loginurl);
                            request.Cookies = loginCookies;
                            request.GetResouceStr();
                        }
                    }
                }
                return true;
            }
            return false;
        }
        public override bool AddSaleHouse(HouseInfo info, ref string targetID)
        {

            UpdateCurrentStatus(StandardProgress.InitalData);
            string error = "";
            try
            {
                if (CheckLogin())
                {
                    string errorInfor = "";
                    if (!CommonCheck(info, true, ref errorInfor))
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, errorInfor);
                        return false;
                    }
                    GetCityID(info);
                    GetCityShort(info);
                    if (loginCookies != null)
                    {
                        loginCookies["ctid"] = CityID;
                    }
                    if (!CheckOutOfLimitaion(true))
                    {
                        string status = "";
                        WebRequest request = new WebRequest("http://my.anjuke.com/user/broker/propertynew/sale/step1/W0QQoooflagZ1");
                        request.Cookies = loginCookies;
                        string hidBrokerId = "";
                        int radSaleType = 1;
                        string str2 = this.GetBrokerID(request.GetResouceStr(), out hidBrokerId, out radSaleType);

                        request = new WebRequest("http://my.anjuke.com/user/broker/property/v7689.jpg");
                        request.Cookies = loginCookies;
                        request.GetResouceStr();

                        request = new WebRequest("http://my.anjuke.com/user/broker/ppc/sale/step1/W0QQoooflagZ1", FormType.FormUrlEncode, Encoding.UTF8, Encoding.UTF8);
                        request.AllowRedirect = true;
                        request.SetHeaderValue("Host", "my.anjuke.com");
                        request.SetHeaderValue("Referer", "http://my.anjuke.com/user/broker/ppc/sale/step1/W0QQoooflagZ1");
                        request.Cookies = loginCookies;

                        request.AddContent("radSaleType", radSaleType.ToString());
                        request.AddContent("hidBrokerID", hidBrokerId);
                        request.AddContent("txtProPrice", info.Price);
                        FillPostData(info, request);

                        UpdateCurrentStatus(StandardProgress.PosData);
                        status = request.SendWaitString();

                        if (!string.IsNullOrEmpty(status))
                        {
                            if (status.Contains("因为您与其他经纪人串号"))
                            {
                                error = "你在安居客上发布的房源已满,不能再发了";
                                goto erroHanlder;
                            }
                            else if (status.Contains("选择的小区不属于该城市"))
                            {
                                error = "选择的小区不属于该城市,请匹配小区后再试!";
                                goto erroHanlder;
                            }
                            else if (status.Contains("抱歉"))
                            {
                                Regex regex = new Regex(@"<h2>(?<msg>[\s\S]*?)</h2>");
                                error = regex.Match(status).Groups["msg"].Value;
                                goto erroHanlder;
                            }
                            if (!string.IsNullOrEmpty(request.ResponUri))
                            {
                                Regex regex = new Regex(@"W0QQpropidZ(\d+)");
                                if (regex.IsMatch(request.ResponUri))
                                {
                                    targetID = regex.Match(request.ResponUri).Groups[1].Value ?? "";
                                }
                                SyncMyImages(info, request.ResponUri, targetID, ref status);

                                UpdateCurrentStatus(StandardProgress.Sucess, GetImageError(info), targetID, "http://" + CityShort + ".anjuke.com/prop/view/" + targetID);
                                return true;
                            }
                        }
                    }
                    else
                    {
                        error = "您发布的新房源已达上限，无法再发布了";
                    }
                }
            }
            catch (System.Net.WebException exp)
            {
                error = WebError;
            }
            catch (Exception exp)
            {
                LogCenter.Log("安居客信息提交", exp);
                error = exp.Message;
            }

        erroHanlder:
            UpdateCurrentStatus(StandardProgress.Failed, error);
            return false;
        }


        public override bool AddRentHouse(HouseInfo info, ref string targetID)
        {

            UpdateCurrentStatus(StandardProgress.InitalData);
            string error = "";
            try
            {
                if (CheckLogin())
                {
                    string errorInfor = "";
                    if (!CommonCheck(info, false, ref errorInfor))
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, errorInfor);
                        return false;
                    }
                    GetCityID(info);
                    GetCityShort(info);
                    if (loginCookies != null)
                    {
                        loginCookies["ctid"] = CityID;
                    }
                    if (!CheckOutOfLimitaion(false))
                    {
                        string status = "";
                        WebRequest request = new WebRequest("http://my.anjuke.com/user/broker/propertynew/rent/step1/W0QQoooflagZ1");

                        request.Cookies = loginCookies;
                        string hidBrokerId = "";
                        int radSaleType = 1;
                        string str2 = this.GetBrokerID(request.GetResouceStr(), out hidBrokerId, out radSaleType);

                        request = new WebRequest("http://my.anjuke.com/user/broker/property/v7689.jpg");
                        request.Cookies = loginCookies;
                        request.GetResouceStr();

                        request = new WebRequest("http://my.anjuke.com/user/broker/ppc/rent/step1/W0QQoooflagZ1", FormType.FormUrlEncode, Encoding.UTF8, Encoding.UTF8);
                        request.AllowRedirect = true;
                        request.SetHeaderValue("Host", "my.anjuke.com");
                        request.SetHeaderValue("Referer", "http://my.anjuke.com/user/broker/ppc/rent/step1/W0QQoooflagZ1");
                        request.Cookies = loginCookies;

                        request.AddContent("radSaleType", radSaleType.ToString());
                        request.AddContent("hidBrokerID", hidBrokerId);

                        FillPostData(info, request);

                        #region Rent Related information

                        FillPayType(info, request);
                        request.AddContent("radIsDolmus", GetHireType(info.HireType));
                        request.AddContent("txtProPrice", info.MonthPrice);
                        #endregion

                        UpdateCurrentStatus(StandardProgress.PosData);
                        status = request.SendWaitString();

                        if (!string.IsNullOrEmpty(status))
                        {
                            if (status.Contains("因为您与其他经纪人串号"))
                            {
                                error = "你在安居客上发布的房源已满,不能再发了";
                                goto erroHanlder;
                            }
                            else if (status.Contains("选择的小区不属于该城市"))
                            {
                                error = "选择的小区不属于该城市,请匹配小区后再试!";
                                goto erroHanlder;
                            }
                            else if (status.Contains("抱歉"))
                            {
                                Regex regex = new Regex(@"<h2>(?<msg>[\s\S]*?)</h2>");
                                error = regex.Match(status).Groups["msg"].Value;
                                goto erroHanlder;
                            }
                            if (!string.IsNullOrEmpty(request.ResponUri))
                            {
                                Regex regex = new Regex(@"W0QQpropidZ(\d+)");
                                if (regex.IsMatch(request.ResponUri))
                                {
                                    targetID = regex.Match(request.ResponUri).Groups[1].Value ?? "";
                                }
                                SyncMyImages(info, request.ResponUri, targetID, ref status);

                                UpdateCurrentStatus(StandardProgress.Sucess, GetImageError(info), targetID, "http://" + CityShort + ".anjuke.com/prop/view/" + targetID);
                                return true;
                            }
                        }
                    }
                    else
                    {
                        error = "您发布的新房源已达上限，无法再发布了";
                    }
                }
            }
            catch (System.Net.WebException exp)
            {
                error = WebError;
            }
            catch (Exception exp)
            {
                LogCenter.Log("安居客信息提交", exp);
                error = exp.Message;
            }

        erroHanlder:
            UpdateCurrentStatus(StandardProgress.Failed, error);
            return false;
        }



        public override bool DeleteSaleHouse(HouseInfo info, string targetID)
        {
            string error = "删除失败";
            try
            {
                string strHouseUrl;
                if (info.TradeType == TradeType.Sale)
                {
                    strHouseUrl = "http://my.anjuke.com/member/brokerpropmanage/W0QQactZsaleQQkwZ" + targetID;
                }
                else
                {
                    strHouseUrl = "http://my.anjuke.com/member/brokerpropmanage/W0QQactZrentQQkwZ" + targetID;
                }
                UpdateCurrentStatus(StandardProgress.InitalData);

                if (!CheckLogin())
                {
                    UpdateCurrentStatus(StandardProgress.Failed, "登录失败");
                    return false;
                }
                else
                {

                    WebRequest request = new WebRequest(strHouseUrl);
                    request.Cookies = loginCookies;
                    string ret = request.GetResouceStr();
                    string brokerId = "";
                    if (!string.IsNullOrEmpty(ret))
                    {
                        Regex regex = new Regex(@"shop\.php\?bid=(?<bid>\d+)");
                        Regex regex2 = new Regex(@"shop/view/(?<bid>\d+)");
                        if (regex.IsMatch(ret))
                        {
                            brokerId = regex.Match(ret).Groups["bid"].Value ?? "";
                        }
                        else if (regex2.IsMatch(ret))
                        {
                            brokerId = regex2.Match(ret).Groups["bid"].Value ?? "";
                        }
                        if (ret.Contains("没有找到符合要求的房子"))
                        {
                            UpdateCurrentStatus(StandardProgress.Failed, "没有找到符合要求的房子");
                            return false;
                        }
                        UpdateCurrentStatus(StandardProgress.PosData);
                        request = new WebRequest("http://my.anjuke.com/user/ppc/brokerpropmanage/W0QQactZsaleQQggZ1", FormType.FormUrlEncode);
                        request.Cookies = loginCookies;
                        request.AddContent("rproid[]", targetID);
                        request.AddContent("ob", brokerId);
                        request.AddContent("propsort", "0,0");
                        request.AddContent("action", "hide");
                        request.AddContent("act", "sale");//
                        request.AddContent("ctype", "0");
                        string str6 = request.SendWaitString();
                        if (!str6.Contains(targetID))
                        {
                            UpdateCurrentStatus(StandardProgress.Sucess, "");
                            return true;
                        }
                        else if (str6.Contains("请您通过审核后"))
                        {
                            UpdateCurrentStatus(StandardProgress.Failed, "房源删除失败,原因：请您通过审核后，再来使用这项功能");
                            return false;
                        }
                    }

                }
            }
            catch (System.Net.WebException exp1)
            {
                error = WebError;
            }
            catch (Exception exp)
            {
                LogCenter.Log("安居客信息删除", exp);
                error = exp.Message;
            }
            UpdateCurrentStatus(StandardProgress.Failed, error);
            return false;
        }

        public override bool DeleteRentHouse(HouseInfo info, string targetID)
        {
            string error = "删除失败";
            try
            {
                string strHouseUrl;
                if (info.TradeType == TradeType.Sale)
                {
                    strHouseUrl = "http://my.anjuke.com/member/brokerpropmanage/W0QQactZsaleQQkwZ" + targetID;
                }
                else
                {
                    strHouseUrl = "http://my.anjuke.com/member/brokerpropmanage/W0QQactZrentQQkwZ" + targetID;
                }
                UpdateCurrentStatus(StandardProgress.InitalData);

                if (!CheckLogin())
                {
                    UpdateCurrentStatus(StandardProgress.Failed, "登录失败");
                    return false;
                }
                else
                {

                    WebRequest request = new WebRequest(strHouseUrl);
                    request.Cookies = loginCookies;
                    string ret = request.GetResouceStr();
                    string brokerId = "";
                    if (!string.IsNullOrEmpty(ret))
                    {
                        Regex regex = new Regex(@"shop\.php\?bid=(?<bid>\d+)");
                        Regex regex2 = new Regex(@"shop/view/(?<bid>\d+)");
                        if (regex.IsMatch(ret))
                        {
                            brokerId = regex.Match(ret).Groups["bid"].Value ?? "";
                        }
                        else if (regex2.IsMatch(ret))
                        {
                            brokerId = regex2.Match(ret).Groups["bid"].Value ?? "";
                        }
                        if (ret.Contains("没有找到符合要求的房子"))
                        {
                            UpdateCurrentStatus(StandardProgress.Failed, "没有找到符合要求的房子");
                            return false;
                        }
                        UpdateCurrentStatus(StandardProgress.PosData);
                        request = new WebRequest("http://my.anjuke.com/user/ppc/brokerpropmanage/W0QQactZrentQQggZ1", FormType.FormUrlEncode);
                        request.Cookies = loginCookies;
                        request.AddContent("rproid[]", targetID);
                        request.AddContent("ob", brokerId);
                        request.AddContent("propsort", "0,0");
                        request.AddContent("action", "hide");
                        request.AddContent("act", "rent");//rent
                        request.AddContent("ctype", "0");
                        string str6 = request.SendWaitString();
                        if (!str6.Contains(targetID))
                        {
                            UpdateCurrentStatus(StandardProgress.Sucess, "");
                            return true;
                        }
                        else if (str6.Contains("请您通过审核后"))
                        {
                            UpdateCurrentStatus(StandardProgress.Failed, "房源删除失败,原因：请您通过审核后，再来使用这项功能");
                            return false;
                        }
                    }

                }
            }
            catch (System.Net.WebException exp1)
            {
                error = WebError;
            }
            catch (Exception exp)
            {
                LogCenter.Log("安居客信息删除", exp);
                error = exp.Message;
            }
            UpdateCurrentStatus(StandardProgress.Failed, error);
            return false;
        }



        #endregion

        #region HelpFunction

        private void FillPostData(HouseInfo info, WebRequest request)
        {
            request.AddContent("hidact", "save");
            request.AddContent("hidCommunityID", GetCommunityID(info.Estate));
            if ((info.Images != null) && (info.Images.Length > 0))
            {
                request.AddContent("chkUploadPic", "1");
            }

            request.AddContent("hidCommunityName", info.Estate);

            request.AddContent("prodraftid", "");
            request.AddContent("propid", "0");

            request.AddContent("protag", "");
            request.AddContent("radFitment", GetDecoration(info.Decoration));
            request.AddContent("radHouseOri", GetToward(info.Toward));

            request.AddContent("radUseType", GetHouseType(info.HouseType));
            request.AddContent("step", "step2");

            request.AddContent("txtAreaNum", info.Area);


            request.AddContent("txtCommunity", info.Estate);
            request.AddContent("txtExplain", "<p>" + info.Description + "<p>");

            request.AddContent("txtFloorNum", info.Floors);
            request.AddContent("txtHallNum", info.Hall);
            request.AddContent("txtHouseAge", info.Age);

            request.AddContent("txtProFloor", info.CurrentFloor);
            request.AddContent("txtProName", info.Title);



            request.AddContent("txtRoomNum", info.Room);
            request.AddContent("txtToiletNum", info.WashRoom);
            request.AddContent("txtUserDefine", "");
            request.AddContent("videoUrl", "");
        }

        private bool CheckOutOfLimitaion(bool isSale)
        {
            string url = "";
            if (isSale)
                url = "http://my.anjuke.com/user/broker/property/sale/step1";
            else
                url = "http://my.anjuke.com/user/broker/property/rent/step1";
            WebRequest request = new WebRequest(url);
            request.Cookies = loginCookies;
            string k = request.GetResouceStr();
            if (k.Contains("已达上限") || k.Contains("已达到上限"))
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        private void GetCityID(HouseInfo info)
        {
            switch (info.City)
            {
                case "上海":
                    CityID = "11";
                    break;
                case "成都":
                    CityID = "15";
                    break;
                case "北京":
                    CityID = "14";
                    break;
                default:
                    CityID = "11";
                    break;
            }
        }

        private void FillPayType(HouseInfo info, WebRequest request)
        {
            //当前 1:付一押一 2:付二押一 3:付三押一 4:付六押一
            switch (info.PayType)
            {
                case "1":
                    request.AddContent("txtPayNum", "1");
                    request.AddContent("txtDepositNum", "1");
                    break;
                case "2":
                    request.AddContent("txtPayNum", "2");
                    request.AddContent("txtDepositNum", "1");
                    break;
                case "3":
                    request.AddContent("txtPayNum", "3");
                    request.AddContent("txtDepositNum", "1");
                    break;
                case "4":
                    request.AddContent("txtPayNum", "6");
                    request.AddContent("txtDepositNum", "1");
                    break;
                default:
                    request.AddContent("txtPayNum", "3");
                    request.AddContent("txtDepositNum", "1");
                    break;
            }
        }
        private void FillPayType(HouseInfo info, out string txtPayNum, out string txtDepositNum)
        {
            //当前 1:付一押一 2:付二押一 3:付三押一 4:付六押一
            switch (info.PayType)
            {
                case "1":
                    txtPayNum = "1";
                    txtDepositNum = "1";
                    break;
                case "2":
                    txtPayNum = "2";
                    txtDepositNum = "1";

                    break;
                case "3":
                    txtPayNum = "3";
                    txtDepositNum = "1";

                    break;
                case "4":
                    txtPayNum = "6";
                    txtDepositNum = "1";

                    break;
                default:
                    txtPayNum = "3";
                    txtDepositNum = "1";
                    break;
            }
        }
        private void GetCityShort(HouseInfo info)
        {
            CityShort = PinyingConvert.Convert(info.City).ToLower();
        }

        public string GetHouseType(string type)
        {
            //房屋类型.平房=1,普通住宅=2,商住两用=3,公寓=4,别墅=5,其他=6
            //老公房 =5,公寓 =1,新里洋房=3,别墅=2
            switch (type)
            {
                case "1":
                case "2":
                case "3":
                case "4":
                    return "1";
                case "5":
                    return "2";
                case "6":
                    return "1";
                default:
                    return "1";
            }
        }

        private string GetHireType(string type)
        {
            //出租方式。0.单间出租 1.床位出租 2.整套出租

            //安居客 1 合租 2 整租 
            if (type == "0" || type == "1")
            {
                return "1";
            }
            return "2";
        }

        public bool SyncMyImages(HouseInfo info, string refurl, string targetID, ref string status)
        {
            try
            {
                errorImage = 0;
                retImages.Clear();
                retImageDes.Clear();
                retImageName.Clear();
                if (info.Images != null && info.Images.Length > 0)
                {
                    WebRequest request = new WebRequest(refurl);
                    request.Cookies = loginCookies;
                    string ret = request.GetResouceStr();
                    Regex regex = new Regex("/user/broker/property/v.*?(?=\\\")");
                    Match ma = regex.Match(ret);
                    if (ma.Success)
                    {
                        request = new WebRequest("http://my.anjuke.com" + ma.Value);
                        request.Cookies = loginCookies;
                        request.GetResouceStr();
                    }

                    request = new WebRequest("http://my.anjuke.com/user/broker/repeatpic", FormType.FormUrlEncode);
                    request.AddContent("proid", targetID);
                    request.Cookies = loginCookies;
                    string containedImage = HtmlHelper.DecodingJSON(request.SendWaitString());
                    //房源基本信息：<img src="/user/broker/property/v42421.gif" width="1" height="1" /></strong>
                    status = "";
                    foreach (string url in info.Images)
                    {
                        string imagename = url.Substring(url.LastIndexOf('/') + 1);
                        #region 上传图片
                        request = new WebRequest(url);
                        byte[] retByte = request.GetResouceByte();
                        string name = url.Substring(url.LastIndexOf('/') + 1);

                        request = new WebRequest("http://upd1.ajkimg.com/upload-anjuke", FormType.MultiPart, Encoding.UTF8, Encoding.GetEncoding("GB2312"));
                        request.SetHeaderValue("Referer", refurl);
                        request.AddContent("comment", "{\"copyright\":\"anjuke\",\"name\":\"爱的\",\"brokerid\":\"847151\"}");
                        request.AddContent("ct", "text/html");
                        request.AddContent("rt", "http://my.anjuke.com/ajax/uploadcallback/");
                        request.AddFile(name, "file", retByte);
                        string temp = request.SendWaitString();

                        temp = temp.Replace("&quot;", "\"");
                        Regex reg = new Regex("(?<=\"id\":\").+?(?=\")");
                        ma = reg.Match(temp);
                        string imgc = "";
                        if (ma.Success)
                        {
                            imgc = ma.Value;
                            //retImages.Add(ma.Value);

                            Regex widthReg = new Regex("(?<=width\":)\\d+");

                            Regex heightReg = new Regex("(?<=height\":)\\d+");
                            Regex sizeReg = new Regex("(?<=size\":)\\d+");
                            string imgdes = ma.Value.Replace("\\", "") + string.Format("|{0}|{1}|{2}", widthReg.Match(temp).Value, heightReg.Match(temp).Value, sizeReg.Match(temp).Value);
                            retImages.Add(imgc);
                            retImageDes.Add(imgdes);
                            retImageName.Add(imagename);
                        }

                        else
                        {
                            errorImage++;
                        }
                        #endregion
                        //{"status":"ok","image":{"host":1,"id":"82239adbb25f96eaa95796536b7dc317","width":640,"height":480,"size":36526,"hash":"82239adbb25f96eaa95796536b7dc317","format":"JPEG","exists":1,"exif":
                        //"a:8:{s:12:\"FileDateTime\";s:10:\"1346232745\";s:8:\"FileSize\";s:5:\"36526\";s:8:\"MimeType\";s:0:\"\";s:4:\"Make\";s:0:\"\";s:5:\"Model\";s:0:\"\";s:8:\"Software\";s:0:\"\";s:8:\"DateTime\";s:10:\"1346232745\";s:9:\"copyright\";i:0;}"}}
                    }
                    //443b7bf0c9c16a6dc352524a9ee77672|http://pic1.ajkimg.com/display/443b7bf0c9c16a6dc352524a9ee77672/100x75.jpg|||1|a:8:{s:12:"FileDateTime";s:10:"1346340937";s:8:"FileSize";s:5:"42323";s:8:"MimeType";s:0:"";s:4:"Make";s:0:"";s:5:"Model";s:0:"";s:8:"Software";s:0:"";s:8:"DateTime";s:10:"1346340937";s:9:"copyright";i:0;}|640|480|42323
                    //e229f1469072e1e97877cb3ba91c9ddc|http://pic1.ajkimg.com/display/e229f1469072e1e97877cb3ba91c9ddc/100x75.jpg|||1|a:8:{s:12:"FileDateTime";s:10:"1346341088";s:8:"FileSize";s:5:"52068";s:8:"MimeType";s:0:"";s:4:"Make";s:0:"";s:5:"Model";s:0:"";s:8:"Software";;s:8:"DateTime";s:10:"1346341088";s:9:"copyright";i:0;}|265|92|52068
                    WebRequest newRequest = new WebRequest(refurl, FormType.FormUrlEncode);
                    newRequest.Cookies = loginCookies;
                    newRequest.AllowRedirect = false;
                    newRequest.AddContent("defaultImgID", "0");
                    newRequest.AddContent("hidact", "savepic");
                    newRequest.AddContent("delComm", "");
                    newRequest.AddContent("delModel", "");
                    newRequest.AddContent("delRoom", "");


                    for (int index = 0; index < retImages.Count; index++)
                    {
                        newRequest.AddContent("file", retImageName[index]);
                        newRequest.AddContent("newupdroom[]", string.Format("{0}|http://pic1.ajkimg.com/display/{1}/100x75.jpg|||1|{2}", retImages[index], retImages[index], retImageDes[index]));
                        newRequest.AddContent("roomorder[]", retImages[index]);
                        newRequest.AddContent(string.Format("dropDesc[{0}]", retImages[index]), "");
                        newRequest.AddContent(string.Format("customDes[{0}]", retImages[index]), "");
                    }

                    string reterror = newRequest.SendWaitString();
                    newRequest = new WebRequest(newRequest.TransferLocation);

                    newRequest.Cookies = loginCookies;
                    status = newRequest.GetResouceStr();
                    if (!(status.IndexOf("继续发布") > -1) && !status.Contains("发布成功！"))
                    {
                        LogCenter.LogMessage("安居客图片提交失败,合发码:" + info.HefaCode);
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
            }
            catch (Exception exp)
            {
                LogCenter.Log("安居客图片提交.合法码:" + info.HefaCode, exp);
                return false;
            }
            return true;
        }

        public string GetDecoration(string dec)
        {
            //当前 1:毛胚 2:简装 3:精装 4:豪装
            //毛坯 =1,简单装修=2,精装修=3,豪华装修=4
            switch (dec)
            {
                case "1":
                    return "1";
                case "2":
                    return "2";
                case "3":
                    return "3";
                case "4":
                    return "4";
                case "5":
                    return "4";
                default:
                    return "2";
            }
        }


        /// <summary>
        /// 从服务器取得编号
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetCommunityID(string name)
        {
            WebRequest request = new WebRequest("http://my.anjuke.com/ajax/community/list2/W0QQcityidZ11", FormType.FormUrlEncode, Encoding.UTF8, Encoding.UTF8);
            request.Cookies = loginCookies;
            request.SetHeaderValue("x-requested-with", "XMLHttpRequest");
            request.AddContent("kw", name);
            string k = request.SendWaitString();
            string p = HtmlHelper.DecodingJSON(k);
            Regex reg = new Regex(@"(?<=""commid"":)\d+");
            Match ma = reg.Match(p);
            if (ma.Success)
            {
                return ma.Value;
            }
            else
            {
                throw new UnMatchEstateException(name);
            }
            //return "13241";
        }
        public string GetToward(string toward)
        {
            //当前 1:东 2:南 3:西 4:北 5:南北 6:东西 7:东南 8:西南 9:东北 10:西北 11:其他
            //目标 0:东 1:南 2:西 3:北 4:东南 5:东北 6:西南 7:西北 8:南北 9:东西

            if (toward == "1")
            {
                return "0";
            }
            if (toward == "2")
            {
                return "1";
            }
            if (toward == "3")
            {
                return "2";
            }
            if (toward == "4")
            {
                return "3";
            }
            if (toward == "5")
            {
                return "8";
            }
            if (toward == "6")
            {
                return "9";
            }
            if (toward == "7")
            {
                return "4";
            }
            if (toward == "8")
            {
                return "6";
            }
            if (toward == "9")
            {
                return "5";
            }
            if (toward == "10")
            {
                return "7";
            }
            return "0";
        }
        private string GetBrokerID(string downHtml, out string hidBrokerId, out int radSaleType)
        {
            hidBrokerId = "";
            radSaleType = 0;
            string str = downHtml ?? "";

            if (!string.IsNullOrEmpty(str))
            {
                hidBrokerId = HtmlHelper.GetTextOrHiddenValueByName(str, "hidBrokerID");
                string pattern = "id=\"radSaleType_(\\d)\"[\\s]*?checked=\"checked\"";
                Regex regex = new Regex(pattern);
                if (regex.IsMatch(str))
                {
                    int.TryParse(regex.Match(str).Groups[1].Value, out radSaleType);
                    if (radSaleType == 0)
                    {
                        radSaleType = 3;
                    }
                }
                if (str.Contains("name=\"radSaleType\" value=\"2\""))
                {
                    radSaleType = 2;
                    return str;
                }
                if (str.Contains("name=\"radSaleType\" value=\"1\""))
                {
                    radSaleType = 1;
                }
            }
            return str;
        }
        #endregion

        #region 编辑功能
        public override bool OpenEidt(WebBrowserOp op, HouseInfo info)
        {
            try
            {
                op.Navigate("http://agent.anjuke.com/login/");
                op.HouseInformation = info;
                op.Completed += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(op_Completed);

            }
            catch
            {
                op.Navigate("http://www.anjuke.com/");
            }
            return true;
        }
        int tryTime = 0;
        void op_Completed(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowserOp op = sender as WebBrowserOp;
            HouseInfo info = op.HouseInformation;
            if (op.innerBrowser.Url.OriginalString.Contains("http://agent.anjuke.com/login/"))
            {
                if (tryTime > 1)
                {
                    tryTime = 0;
                    return;
                }
                else
                {
                    tryTime++;
                }
                op.SetValueByID("loginName", UserName);
                op.SetValueByID("password", Password);
                op.RaiseOpByAttribute("value", "登 录", "click");
            }
            if (op.innerBrowser.Url.OriginalString.Contains("http://my.anjuke.com/user/broker/checked/"))
            {
                if (info.TradeType == TradeType.Sale)
                {

                    string post = "http://my.anjuke.com/user/broker/propertynew/sale/step1/W0QQoooflagZ1";
                    op.HouseInformation = info;
                    op.Navigate(post);
                }
                else
                {
                    
                    string post = "http://my.anjuke.com/user/broker/propertynew/rent/step1/W0QQoooflagZ1";
                    op.HouseInformation = info;
                    op.Navigate(post);
                }
            }
            if (op.innerBrowser.Url.OriginalString.Contains("http://my.anjuke.com/user/broker/ppc/sale/step1")
                || op.innerBrowser.Url.OriginalString.Contains("http://my.anjuke.com/user/broker/propertynew/sale/step1"))
            {
                WebBrowserOp cl = op;
                cl.SetValueByID("txtCommunity", info.Estate);

                cl.SetValueByID("txtAreaNum", info.Area);

                cl.SetValueByID("txtProPrice", info.Price);

                cl.SetValueByID("txtRoomNum", info.Room);
                cl.SetValueByID("txtHallNum", info.Hall);
                cl.SetValueByID("txtToiletNum", info.WashRoom);

                cl.SelectByID_Value("radUseType", GetHouseType(info.HouseType));
                cl.SelectByID_Value("radFitment", GetDecoration(info.Decoration));
                cl.SelectByID_Value("radHouseOri", GetToward(info.Toward));

                cl.SetValueByID("txtProFloor", info.CurrentFloor);
                cl.SetValueByID("txtFloorNum", info.Floors);
                cl.SetValueByID("txtHouseAge", info.Age);

                cl.SetValueByID("txtProName", info.Title);
                cl.SetCKEditorHtml(info.Description);
                //cl.ExcuteScript("CKEDITOR.dom.element('p').setHtml('" + info.Description + "');");
            }
            if (op.innerBrowser.Url.OriginalString.Contains("http://my.anjuke.com/user/broker/ppc/rent/step1")
                || op.innerBrowser.Url.OriginalString.Contains("http://my.anjuke.com/user/broker/propertynew/rent/step1"))
            {
                WebBrowserOp cl = op;
                cl.SetValueByID("txtCommunity", info.Estate);
                cl.CheckByName_Value("radIsDolmus", "2", true);
                

                cl.SetValueByID("txtProPrice", info.MonthPrice);
                string payNum="";
                string depositNum ="";
                FillPayType(info, out payNum, out depositNum);
                cl.SetValueByID("txtPayNum", payNum);
                cl.SetValueByID("txtDepositNum", depositNum);

                cl.SetValueByID("txtAreaNum", info.Area);

                cl.SetValueByID("txtRoomNum", info.Room);
                cl.SetValueByID("txtHallNum", info.Hall);
                cl.SetValueByID("txtToiletNum", info.WashRoom);

                cl.SetValueByID("txtProFloor", info.CurrentFloor);
                cl.SetValueByID("txtFloorNum", info.Floors);

                cl.SelectByID_Value("radUseType", GetHouseType(info.HouseType));
                cl.SelectByID_Value("radFitment", GetDecoration(info.Decoration));
                cl.SelectByID_Value("radHouseOri", GetToward(info.Toward));

              
                cl.SetValueByID("txtHouseAge", info.Age);

                cl.SetValueByID("txtProName", info.Title);
                //cl.SetHtmlByAttribute("class", "cke_show_borders", info.Description);
                cl.SetCKEditorHtml(info.Description);
                
            }
        }
      
    
        #endregion
    }
}
